package com.crm.controller.adminController;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.crm.dao.SupplierDAO;
import com.crm.entity.Business;
import com.crm.entity.Supplier;
import com.crm.entity.SupplierUser;
@Controller
@RequestMapping("/supplier")
public class SupplierController {
	protected final Log logger = LogFactory.getLog(getClass());
	SupplierDAO supplierDAO=new SupplierDAO();
	List<Supplier> suppliersList=new ArrayList<Supplier>();
	Supplier supplier=null;
	
	@RequestMapping("/open.do")
	public ModelAndView open(HttpSession session,ModelAndView model){
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		
		try {
			suppliersList=supplierDAO.findAll(busid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model=new ModelAndView("/jsp/Supplier.jsp")
		.addObject("submenu", "admin")
		.addObject("menuName","admin")
		.addObject("supList",suppliersList);
		return model;
		
	}
	
	@RequestMapping(value="/save.do",method = RequestMethod.POST)
	public ModelAndView insert(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String sourceName=req.getParameter("sname");
		String email=req.getParameter("email");
		String phno=req.getParameter("phno");
		String website=req.getParameter("website");
		String address=req.getParameter("address");
		String fax=req.getParameter("fax");
		
		String rcount=req.getParameter("rowcount");
		logger.info("the row count is"+rcount);
		int rowcount=Integer.parseInt(rcount);
		supplier=new Supplier(bus,sourceName,email,phno,null,website,address,fax,false);


		Set<SupplierUser> setSup=new HashSet<SupplierUser>();
			
		
		for(int i=1;i<=rowcount;i++){
			String cName=req.getParameter("cperson"+i);
			String phone=req.getParameter("phone"+i);
			String mail=req.getParameter("email"+i);
			try {
				SupplierUser suser= new SupplierUser(supplier,cName,phone,mail);
				setSup.add(suser);
			} catch (NullPointerException e) {
				e.printStackTrace();
			}
			
		}
		supplier.setSuppuser(setSup);
		String msg=null;
		try{
			supplierDAO.insert(supplier);
			msg="Successfully Saved Supplier Details";
		}catch(Exception ex){
			ex.printStackTrace();
			msg="Failed To Save Supplier Details.Please Try Again.";
		}
		model.addObject("supplierdet",msg);
		model.setViewName("redirect:open.do");
		return model;

	}
	@RequestMapping("/edit.do")
	public @ResponseBody String  editSupplier(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		suppliersList=supplierDAO.findAll(bus.getBusinessId());
		
		StringBuilder  sb=new StringBuilder();
		Iterator<Supplier> is=suppliersList.iterator();
		while(is.hasNext()==true){
			Supplier su=(Supplier)is.next();
			sb.append(su.getName());
			sb.append(",");
		}
		return sb.toString();
	}
	@RequestMapping("/search.do")
	public ModelAndView searchCompany(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ssupplier=request.getParameter("supname");
		logger.info("Supplier name In DAO Is:"+ssupplier);
		
		supplier=supplierDAO.getSupplier(ssupplier,bus.getBusinessId());
		//List<SupplierUser>sUserList=s.getSuppuser();
		
		List<SupplierUser> suppliersList=supplierDAO.getUser(supplier.getId(),bus.getBusinessId());
		ModelAndView model = new ModelAndView("/jsp/editSupplier.jsp");
		model.addObject("supplier",supplier);
		model.addObject("supplier-user",suppliersList);
		model.addObject("submenu", "admin");
		model.addObject("menuName","admin");
		model.setViewName("/jsp/editSupplier.jsp");
		return model;

	}
	@RequestMapping(value="/editsave.do",method = RequestMethod.POST)
	public ModelAndView update(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String suppid=req.getParameter("supplierId");
		String sourceName=req.getParameter("sname");
		String email=req.getParameter("email");
		String phno=req.getParameter("phno");
		String website=req.getParameter("website");
		String address=req.getParameter("address");
		String fax=req.getParameter("fax");
		
		String rcount=req.getParameter("editrowcount");
		logger.info("the row count is"+rcount);
		int rowcount=Integer.parseInt(rcount);
		int supid=Integer.parseInt(suppid);
		logger.info("Supplier Id Is:"+supid);
		supplier=new Supplier(bus,sourceName,website,email,fax,phno,address,null,false);
		supplier.setId(supid);
		supplier.setBusinessId(bus);
		
		Set<SupplierUser> supSet=new HashSet<SupplierUser>();
		for(int i=1;i<=rowcount;i++){
			String cName=req.getParameter("cperson"+i);
			String phone=req.getParameter("phone"+i);
			String mail=req.getParameter("email"+i);
			String supId=req.getParameter("supId"+i);			
			int suserid=0;
			if (supId!=null) {
				suserid = Integer.parseInt(supId);
			}
			
			SupplierUser su= new SupplierUser(supplier,cName,phone,mail);
			if (suserid!=0) {
				su.setId(suserid);
			}
			supSet.add(su);
		}
		supplier.setSuppuser(supSet);
		logger.info("Before Insert Of Supplier:"+supid);
			
		
			logger.info("After Insert Of Supplier:"+supid);
		
			logger.info("Supplier Id In Controller Is:"+supid);
			String msg=null;
			try{
				supplierDAO.insert(supplier);
				msg="Successfully Updated Supplier Details";
			}catch(Exception ex){
				ex.printStackTrace();
				msg="Failed To Update Supplier Details.Please Try Again";
			}
			model.addObject("supplierdet",msg);
			model.addObject("submenu", "admin");
			model.addObject("menuName","admin");
		model.setViewName("/jsp/Supplier.jsp");
		return model;

	}


	@RequestMapping("/delete.do")
	public ModelAndView delete(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		suppliersList=supplierDAO.findAll(bus.getBusinessId());
		
		ModelAndView model = new ModelAndView("/jsp/deleteSupplier.jsp");
		model.addObject("supplier-List",suppliersList);
		model.addObject("submenu", "admin");
		model.addObject("menuName","admin");
		model.setViewName("/jsp/deleteSupplier.jsp");
		return model;
	}
	@RequestMapping("/deleteSupplier.do")
	public ModelAndView deleteSupplier(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		
		String supplierName=request.getParameter("supname");
		supplier=supplierDAO.getByName(supplierName,bus.getBusinessId());
		
		String msg=null;
		ModelAndView model = new ModelAndView("/jsp/Supplier.jsp");
		
		try{
			supplierDAO.deleteSupplier(supplier.getId(),bus.getBusinessId());
			msg="Successfully Deleted Supplier Details";
		}catch(Exception ex){
			ex.printStackTrace();
			msg="Failed To Delete Supplier Details.Please Try Again.";
		}
		model.addObject("supplierdet",msg);
		model.addObject("submenu", "admin");
		model.addObject("menuName","admin");
		model.setViewName("/jsp/Supplier.jsp");
		return model;
	}
	
}
